package com.iter.devbox.pattern.flyweight;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**复合享元工厂角色类 */
public class CompositeFlyweightFactory {

	/**状态所对应的享元对象的集合 */
	private Map<String, Flyweight> cache = new HashMap<String, Flyweight>();

	/**复合享元工厂方法*/
	public Flyweight factory(List<String> compositeState) {
		ConcreteCompositeFlyweight compositeFly = new ConcreteCompositeFlyweight();
		for (String state : compositeState) {
			compositeFly.add(state, this.factory(state));
		}
		return compositeFly;
	}

	/**单纯享元工厂方法*/
	public Flyweight factory(String state) {
		//先从缓存中查找Flyweight对象
		Flyweight fly = cache.get(state);
		if (fly == null) {
			//如果对象不存在则创建一个新的Flyweight对象
			fly = new ConcreteFlyweight(state);
			//把这个新的Flyweight对象添加到缓存中
			cache.put(state, fly);
		}
		return fly;
	}
}